package com.cndongtai.controller.firmware;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cndongtai.constant.SystemConstant;
import com.cndongtai.constant.UserConstant;
import com.cndongtai.controller.BaseController;
import com.cndongtai.po.Firmware;
import com.cndongtai.po.User;
import com.cndongtai.service.firmware.FirmwareService;
import com.cndongtai.util.DESUtil;
import com.cndongtai.util.ValidateUtil;
import com.cndongtai.vo.FirmwareBean;

@Controller
public class FirmwareController extends BaseController {
	
	@Resource(name="firmwareService")
	private FirmwareService firmwareService;
	
	@RequestMapping("/downloadFirmware")
	@ResponseBody
	public void downloadFirmware() {
		String version = this.getValue("version");
		
		try {
			version = DESUtil.defaultDecrypt(version);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			// 文件不存在，返回错误
			StringBuffer script = new StringBuffer("<script type=\"text/javascript\">");
			script.append("alert('该文件不存在001');history.back();");
			script.append("</script>");
			response.setContentType("text/html; charset=utf-8");
			this.writeData(script.toString());
			return;
		}
		
		Long firmwareId = null;
		try {
			firmwareId = Long.valueOf(version);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		if(firmwareId==null) {
			// 文件不存在，返回错误
			StringBuffer script = new StringBuffer("<script type=\"text/javascript\">");
			script.append("alert('该文件不存在002');history.back();");
			script.append("</script>");
			response.setContentType("text/html; charset=utf-8");
			this.writeData(script.toString());
			return;
		}
		
		// 获取固件信息
		Firmware firmware = firmwareService.queryFirmwareById(firmwareId);
		
		String[] files = firmware.getUrl().split("/");
		if(files.length<1) {
			// 文件不存在，返回错误
			StringBuffer script = new StringBuffer("<script type=\"text/javascript\">");
			script.append("alert('该文件不存在003');history.back();");
			script.append("</script>");
			response.setContentType("text/html; charset=utf-8");
			this.writeData(script.toString());
			return;
		}
		
		String fileName = files[files.length-1];
		
		File file = new File(SystemConstant.FILE_FIRMWARE_PATH+File.separator+firmware.getUrl()); //根据该路径创建文件对象
		// 判断文件是否存在
		if(file.exists()) {
			InputStream in = null;
			OutputStream os = null;
			byte[] temp=new byte[1024];
			
			try {
				in = new FileInputStream(file);
				os = response.getOutputStream(); //创建输出流对象
				response.addHeader("Content-Disposition", "attachment;filename="
						+ new String(fileName.getBytes("utf-8"),"iso-8859-1")); //设置应答头信息
				response.addHeader("Content-Length", file.length() + "");
				response.setCharacterEncoding("utf-8"); 
				response.setContentType("application/octet-stream");
				while (in.read(temp) != -1) { //循环读取文件
					os.write(temp); //向指定目录中写文件
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(null != os) {
						os.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else {
			// 文件不存在，返回错误
			StringBuffer script = new StringBuffer("<script type=\"text/javascript\">");
			script.append("alert('该文件不存在004');history.back();");
			script.append("</script>");
			response.setContentType("text/html; charset=utf-8");
			this.writeData(script.toString());
		}
	}
	
	@RequestMapping("/uploadFirmware")
	@ResponseBody
	public void uploadFirmware() {
		JSONObject result = new JSONObject();
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		if(!"admin".equals(loginUser.getUsername())) {
			result.put("success", "-1");
			result.put("msg","权限不够");
			this.writeData(result);
			return;
		}
		
		String firmwareName = this.getValue("firmwareName");
		String protocalVersion = this.getValue("protocalVersion");
		String hardwareVersion = this.getValue("hardwareVersion");
		String firmwareVersion = this.getValue("firmwareVersion");
		String description = this.getValue("description");
		String url = this.getValue("url");
		
		
		// 数据校验
		if(ValidateUtil.empty(firmwareName)) {
			result.put("success", "-1");
			result.put("msg", "固件名称不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(protocalVersion)) {
			result.put("success", "-1");
			result.put("msg", "协议版本号不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(hardwareVersion)) {
			result.put("success", "-1");
			result.put("msg", "硬件版本号不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(firmwareVersion)) {
			result.put("success", "-1");
			result.put("msg", "软件版本不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(description)) {
			result.put("success", "-1");
			result.put("msg", "描述不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(url)) {
			result.put("success", "-1");
			result.put("msg", "请上传固件文件");
			this.writeData(result);
			return;
		}
		
		Firmware firmware = new Firmware();
		firmware.setFirmwareName(firmwareName);
		firmware.setProtocalVersion(protocalVersion);
		firmware.setHardwareVersion(hardwareVersion);
		firmware.setFirmwareVersion(firmwareVersion);
		firmware.setDescription(description);
		firmware.setUrl(url);
		firmware.setCreateBy(loginUser.getUserId());
		firmware.setCreateTime(new Date());
		firmware.setState(0);
		
		boolean addResult = firmwareService.addFirmware(firmware);
		if(addResult) {
			result.put("success", "0");
			result.put("msg", "固件添加成功");
		}else {
			result.put("success", "-1");
			result.put("msg", "固件添加失败");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/delFirmware")
	@ResponseBody
	public void delFirmware() {
		JSONObject result = new JSONObject();
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		if(!"admin".equals(loginUser.getUsername())) {
			result.put("success", "-1");
			result.put("msg","权限不够");
			this.writeData(result);
			return;
		}
		
		String idStr = this.getValue("id");
		
		// 数据校验
		if(ValidateUtil.empty(idStr)) {
			result.put("success", "-1");
			result.put("msg", "请选择要删除的固件");
			this.writeData(result);
			return;
		}
		
		Long id = null;
		try {
			id = Long.valueOf(idStr);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		if(id==null) {
			result.put("success", "-1");
			result.put("msg", "请选择要删除的固件");
			this.writeData(result);
			return;
		}
		
		Firmware firmware = new Firmware();
		firmware.setId(id);
		
		boolean addResult = firmwareService.deleteFirmware(firmware);
		if(addResult) {
			result.put("success", "0");
			result.put("msg", "删除成功");
		}else {
			result.put("success", "-1");
			result.put("msg", "删除失败");
		}
		
		this.writeData(result);
	}
	
	
	@RequestMapping("/showFirmwareList")
	public String showFirmwareList() {
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		
		if(loginUser!=null && "admin".equals(loginUser.getUsername())) {
			List<FirmwareBean> firmwareList = firmwareService.queryFirmwareList();
			request.setAttribute("firmwareList", firmwareList);
		}
		
		return "/firmware/firmwareList";
	}
	

}
